using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Menu;
using Sedna.Core.Globalization;
using Sedna.Core.Tiles.Contents;

namespace Sedna.Core.Controls
{
	public class LeftMenu : WebControl, IContent, IConfigurationAware
	{

		private IMenu menu;
		private string configurationId = "configuration.Menu";//default name in a Spring Context

		private String contentPlaceHolderId;

		public String ContentPlaceHolderId
		{
			get { return contentPlaceHolderId;}
			set { contentPlaceHolderId = value;}
		}

		public IConfiguration Configuration
		{
			get { return menu; }
			set { menu = (IMenu)value; }
		}

		public string ConfigurationId
		{
			get { return configurationId; }
			set { configurationId = value; }
		}

		private HtmlInputHidden hiddenActiveMenu;


		public LeftMenu()
		{
			menu = (IMenu)SpringContextFactory.GetContext().GetObject(configurationId);
		}


		protected override void OnInit(EventArgs e)
		{
			hiddenActiveMenu = new HtmlInputHidden();
			hiddenActiveMenu.ID = "menu_level_2";
			hiddenActiveMenu.EnableViewState = false;
			hiddenActiveMenu.ServerChange += new EventHandler(OnHiddenChange);
			SetUpHiddenActiveMenu();
			Build(this);
			base.OnInit (e);
		}

		protected override void OnPreRender(EventArgs e)
		{
			ActivateMenuItem();
			base.OnPreRender (e);
		}


	    
		protected void Build(Control parent)
		{
		    parent.Controls.Add(new System.Web.UI.LiteralControl("<tr height=\"62\"><td colspan=\"2\" class=\"menuitem\">&nbsp;</td></tr>"));
		    
		    
			IMenuItem topMenuItem = ExtractActiveTopMenuItem();
			topMenuItem.LoadMenuItems(Context, ExecutionContext.GetCurrent(ClientID), "leftMenu");

			foreach(IMenuItem menuItem in topMenuItem.MenuItems)
			{
				if(!menuItem.IsVisibleForPrincipal())
				{
					continue;
				}

				TableRow tr = new TableRow();
				parent.Controls.Add(tr);
				TableCell tdImg = new TableCell();
				tdImg.ID = "tdImg_" + menuItem.Id;
				tdImg.EnableViewState = false;
				tr.Controls.Add(tdImg);
				System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
				img.ID = "img_" + menuItem.Id;
				img.EnableViewState = false;
				tdImg.Controls.Add(img);
				img.ImageUrl = ImageManager.Relate(img, "s.gif");
				img.Width = 14;
				img.Height = 1;
				img.ImageAlign = ImageAlign.AbsMiddle;

				TableCell tdLb = new TableCell();
				tdLb.ID = "tdLb_" + menuItem.Id;
				tdLb.EnableViewState = false;
				tr.Controls.Add(tdLb);
				tdLb.CssClass = menuItem.IsStatic?"menuitemstatic":"menuitem";
				tdLb.Width = Unit.Pixel(116);

				if(!menuItem.IsStatic)
				{
					System.Web.UI.WebControls.LinkButton linkButton = new System.Web.UI.WebControls.LinkButton();
					tdLb.Controls.Add(linkButton);
					linkButton.Text = menuItem.GetLocalizedLabel();
					linkButton.ID = menuItem.Id;
					linkButton.Click += new EventHandler(OnMenuClicked);
					linkButton.Enabled = menuItem.IsEnabledForPrincipal();
					linkButton.Style.Add("text-decoration", "none");
					linkButton.CausesValidation = menuItem.CausesValidation;
				}
				else
				{
				    tdLb.Controls.Add(new System.Web.UI.LiteralControl(menuItem.GetLocalizedLabel()));
				}

			}
		    parent.Controls.Add(hiddenActiveMenu);
			parent.Controls.Add(new System.Web.UI.LiteralControl("<tr height=\"100%\"><td class=\"menuitem\" colspan=\"2\">&nbsp;</td></tr>"));
            
		    
		    TableRow bannerRow = new TableRow();
		    TableCell bannerCell = new TableCell();
            bannerRow.Cells.Add(bannerCell);
		    bannerCell.ColumnSpan = 2;
            bannerCell.CssClass = "menuitembanner";
            bannerCell.HorizontalAlign = HorizontalAlign.Center;
            System.Web.UI.WebControls.Image banner_img = new System.Web.UI.WebControls.Image();
            banner_img.ID = "img_banner";
            banner_img.EnableViewState = false;
            bannerCell.Controls.Add(banner_img);
            banner_img.ImageUrl = ImageManager.Relate(banner_img, "Logo.png");
            //banner_img.Width = Unit.Pixel(80);
            //banner_img.Height = Unit.Pixel(50);
            banner_img.ImageAlign = ImageAlign.AbsMiddle;
		    
		    parent.Controls.Add(bannerRow);
        }

		private void SetUpHiddenActiveMenu()
		{
			string activeLeftMenu = MenuUtils.ExtractMenuLevel2Param(ExecutionContext.Current);
			if(activeLeftMenu != null && string.Empty != activeLeftMenu)
			{
				//check if current menu_level_2 is a child of a current menu_level_1
				if(ExtractActiveTopMenuItem().GetMenuItemById(activeLeftMenu) != null)
				{
					hiddenActiveMenu.Value = activeLeftMenu;
					return;
				}
				//else fall back to a default one
			}
			IMenuItem defaultMenuItem = ExtractActiveTopMenuItem().GetDefaultMenuItem();
			hiddenActiveMenu.Value = defaultMenuItem!=null?defaultMenuItem.Id:"menu_fake_id_level_2";
		}


		private IMenuItem ExtractActiveTopMenuItem()
		{
			string activeTopMenu = ExtractMenuLevel1Param();
			foreach(IMenuItem menuItem in menu.MenuItems)
			{
				if(menuItem.Id == activeTopMenu)
				{
					return menuItem;
				}
			}

			//return (IMenuItem)menu.MenuItems[0];
			return menu.Empty;
		}


		private void OnMenuClicked(object sender, System.EventArgs e)
		{
			IMenuItem menuItem = menu.GetMenuItemById(((Control)sender).ID);
			hiddenActiveMenu.Value = menuItem.Id;

			IActionExecutor actionExecutor = (IActionExecutor)SpringContextFactory.GetContext().GetObject("runtime.ActionExecutor");
			IExecutionContext executionContext = ExecutionContext.GetCurrent(ClientID);
			executionContext["menu_level_1"] = ExtractMenuLevel1Param();
			executionContext["menu_level_2"] = menuItem.Id;

			actionExecutor.ExecuteAction(executionContext, menuItem, this.ClientID);

		}

		private void ActivateMenuItem()
		{
			IMenuItem menuItem = menu.GetMenuItemById(hiddenActiveMenu.Value);
			if(menuItem == null)
			{
				return;
			}
			TableCell tdLb = (TableCell)FindControl("tdLb_" + menuItem.Id);
			tdLb.CssClass = "menuitemselected";
			tdLb.VerticalAlign = VerticalAlign.Middle;
			TableCell tdImg = (TableCell)FindControl("tdImg_" + menuItem.Id);
			tdImg.CssClass = "rightalign";
			tdImg.Width = Unit.Pixel(16);
			System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)FindControl("img_" + menuItem.Id);
			img.BorderWidth = 0;
			img.ImageUrl = ImageManager.Relate(img, "menuedge.gif");
			img.Width = Unit.Empty;
			img.Height = Unit.Empty;
			System.Web.UI.WebControls.LinkButton linkButton = (System.Web.UI.WebControls.LinkButton)FindControl(menuItem.Id);
			if(linkButton != null)
			{
				linkButton.CssClass = "menuitemselected";
			}
			Context.Session["infrastructure.menu_level_2"] = menuItem.Id;
		}

		private void OnHiddenChange(object sender, System.EventArgs e)
		{
			SetUpHiddenActiveMenu();
		}

		private string ExtractMenuLevel1Param()
		{
			string menu_level_1= Context.Request.Form["new_menu_level_1"];
			if (menu_level_1==null||String.Empty.Equals(menu_level_1))
			{
				menu_level_1 = Context.Request.QueryString["menu_level_1"];
			}
			return menu_level_1;
			
//			if(menu_level_1 == null || menu_level_1 == string.Empty)
//			{
//				return menu_level_1;
//			}
//			if(menu_level_1.IndexOf(',', 0) < 0)
//			{
//				return menu_level_1;
//			}
//			return menu_level_1.Substring(menu_level_1.LastIndexOf(',') + 1);

		}



	}
}
